package com.fancon.android.gardenjokesx.activity;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

import com.fancon.android.gardenjokesx.GardenJokesBaseActivity;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.adapter.TmpAdapter;
import com.fancon.android.gardenjokesx.dialog.FirstLaunchDialog;
import com.fancon.android.gardenjokesx.entity.Photo;
import com.fancon.android.gardenjokesx.rpc.JsonPaser;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.multithread.RequestUI;

public class SplashScreenActivity extends GardenJokesBaseActivity {
	private ListView mList;
	private ArrayList<Photo> listPhotos = new ArrayList<Photo>();
	private TmpAdapter adapter = null;
	private Boolean isFirst = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.init);
		SharedPreferences settings = getSharedPreferences(
				Constant.PREFS_REGISTER, 0);
		if (settings.getString(Constant.REGISTRATION_ID, "").equals("")) {
			registerPush();
		}
		mList = (ListView) findViewById(R.id.lst_id);
		mList.setCacheColorHint(0);
		JokesDataRequest photoReq = new JokesDataRequest("photo_rq", this);
		getGlobalState().getRequestQueue().addRequest(photoReq);
	}

	@Override
	public void onResume() {
		super.onResume();
		SharedPreferences sett = getSharedPreferences(Constant.PREFS_NAME, 0);
		if (!sett.getString(Constant.USER_ID_LOGIN, "null").equals("null")) {
			if (isFirst) {
				isFirst = false;
				Log.d("share", "share");
				Intent intent = new Intent(getApplicationContext(),
						GardenJokesActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				getApplicationContext().startActivity(intent);
			}else{
				finish();
			}
		} else {
			FirstLaunchDialog dialog = new FirstLaunchDialog(this);
			dialog.show();
		}
	}
	@Override
	public void onPause(){
		super.onPause();
		isFirst = false;
	}
	public void registerPush() {
		Log.d("Push", "dang ki Push");
		Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER");
		intent.putExtra("app",
				PendingIntent.getBroadcast(this, 0, new Intent(), 0));
		// Sender currently not used
		intent.putExtra("sender", "falcon.gardenjokes@gmail.com");
		startService(intent);
	}

	private void loadDataView() {
		if (adapter == null) {
			adapter = new TmpAdapter(this, listPhotos);
			mList.setAdapter(adapter);
		} else {
			adapter.notifyDataSetChanged();
		}
	}

	private String loadRawData(int resId) throws Exception {
		InputStream is = getResources().openRawResource(resId);
		Writer writer = new StringWriter();
		char[] buffer = new char[1024];
		try {
			Reader reader = new BufferedReader(new InputStreamReader(is,
					"UTF-8"));
			int n;
			while ((n = reader.read(buffer)) != -1) {
				writer.write(buffer, 0, n);
			}
		} finally {
			is.close();
		}

		String jsonString = writer.toString();
		return jsonString;
	}

	class JokesDataRequest extends RequestUI {
		private ArrayList<Photo> tmp;

		public JokesDataRequest(Object key, Activity activity) {
			super(key, activity);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void execute() throws Exception {
			try {
				String result = loadRawData(R.raw.data);
				Log.v("StringResult", result);
				JsonPaser jP = new JsonPaser();
				tmp = jP.getListPhotoDetail(result);
				Log.v("StringResultSize", " " + tmp.size());
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub

			try {
				if (tmp.size() > 0) {
					if (listPhotos.size() > 0) {
						listPhotos.addAll(tmp);
					} else {
						listPhotos = tmp;
					}
				}
			loadDataView();
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}

	}

	public void onDestroy() {
		super.onDestroy();
			/*
			 * Notify the system to finalize and collect all objects of the
			 * application on exit so that the process running the application
			 * can be killed by the system without causing issues. NOTE: If this
			 * is set to true then the process will not be killed until all of
			 * its threads have closed.
			 */
			System.runFinalizersOnExit(true);

			/*
			 * Force the system to close the application down completely instead
			 * of retaining it in the background. The process that runs the
			 * application will be killed. The application will be completely
			 * created as a new application in a new process if the user starts
			 * the application again.
			 */
			System.exit(0);
	}
}
